package com.smart.manager.wiki.entities.repository;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Opt;
import com.smart.common.entities.constant.ArcoTips;
import com.smart.common.entities.core.Page;
import com.smart.manager.wiki.entities.body.RPopHelp;
import com.smart.manager.wiki.entities.enums.HelpKind;
import com.smart.manager.wiki.entities.models.WikiPopHelp;
import com.smart.manager.wiki.entities.models.query.QWikiPopHelp;
import io.ebean.DB;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 帮助中心
 * @author leo
 * @date 2023/07/26
 */
@Service
@Log4j2
@RequiredArgsConstructor
public class PopHelpRepository {

    /**
     * 查询搜索
     * @param search 搜索
     * @return {@link Page}<{@link WikiPopHelp}>
     */
    public Page<WikiPopHelp> pageList(RPopHelp.SearchBody search) {
        QWikiPopHelp query = new QWikiPopHelp();
        Opt.ofBlankAble(search.getKind()).ifPresent(x -> query.kind.eq(x));
        Opt.ofBlankAble(search.getTitle()).ifPresent(x -> query.title.contains(x));
        query.setFirstRow(search.firstRow()).setMaxRows(search.maxRows());
        return new Page<WikiPopHelp>().load(query.findPagedList());
    }

    /**
     * 添加
     * @param body 身体
     */
    public void add(RPopHelp.EditBody body) {
        QWikiPopHelp query = new QWikiPopHelp();
        WikiPopHelp record = query.title.eq(body.getTitle()).setMaxRows(1).findOne();
        Assert.isNull(record, "创建失败:, 标题已存在");
        BeanUtil.copyProperties(body, WikiPopHelp.class).save();
    }

    /**
     * 更新
     * @param id   id
     * @param body 身体
     */
    public void update(Long id, RPopHelp.EditBody body) {
        QWikiPopHelp query = new QWikiPopHelp();
        WikiPopHelp record = query.id.eq(id).setMaxRows(1).findOne();
        Assert.notNull(record, ArcoTips.UPDATE_NOT_FOUND);
        BeanUtil.copyProperties(body, record);
        Objects.requireNonNull(record).update();
    }

    /**
     * 删除ids
     * @param ids id
     * @return int
     */
    public int delByIds(List<Long> ids) {
        List<WikiPopHelp> list = new QWikiPopHelp().id.in(ids).findList();
        Assert.notEmpty(list, ArcoTips.DELETE_NOT_FOUND);
        for (WikiPopHelp module : list) {
            log.warn("检查数据是否允许被删除  {}", module);
        }
        return DB.deleteAll(list);
    }


    /**
     * 前端获取
     * @return {@link List}<{@link WikiPopHelp}>
     */
    public List<WikiPopHelp> getList() {
        return new QWikiPopHelp().findList();
    }

    /**
     * 前端获取公告
     * @return {@link List}<{@link WikiPopHelp}>
     */
    public List<WikiPopHelp> getBulletinList() {
        return new QWikiPopHelp().kind.eq(HelpKind.ANNOUNCEMENT).findList();
    }
}
